package com.ruoyi.web.controller.wechatmp;

import com.ruoyi.ai.api.OpenAiApi;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.config.WeChatMpConfig;
import com.ruoyi.common.enums.WxMpMsgType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.wechatmp.WechatMpXmlUtil;
import com.ruoyi.custom.strategy.wechatmp.WechatMpMessageHandleStrategy;
import com.ruoyi.custom.strategy.wechatmp.WechatMpMessageHandleStrategyFactory;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

/**
 * @author xudm
 * @description 微信公众平台对接控制器
 * @date 2024-09-27  13:59
 */
@RestController
@RequestMapping("/wechatmp/messageHandle")
@Slf4j
@Anonymous
public class WechatMpController {
    @Resource
    private WeChatMpConfig weChatMpConfig;

    /**
     * 消息处理
     *
     * @author xudm
     * @date 2024/9/27 14:08
     **/
    @GetMapping("")
    public String mseeageHandle(HttpServletRequest request) {
        String echostr = request.getParameter("echostr");
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String token = weChatMpConfig.getToken();
        if (StringUtils.isEmpty(echostr) || StringUtils.isEmpty(signature) || StringUtils.isEmpty(timestamp) || StringUtils.isEmpty(nonce)) {
            return "error";
        }
        // 验证签名
        if (!checkSignature(signature, timestamp, nonce, token)) {
            return "error signature";
        }
        return echostr;
    }

    @PostMapping()
    public void handleMessage(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        String xml = sb.toString();
        log.info("接收到的消息：" + xml);
        // 处理接收到的消息
        String msgType = WechatMpXmlUtil.getMsgType(xml);
        log.info("接收到的消息类型：" + msgType);
        // 根据消息类型调用相应的处理策略
        // 这里可以根据消息类型调用相应的处理策略，例如：
        String responseMessage = WechatMpXmlUtil.generateResponseXml(xml, "消息策略配置错误");
        // 根据消息类型获取对应的处理策略
        WxMpMsgType wxMpMsgType = WxMpMsgType.fromValue(msgType);
        WechatMpMessageHandleStrategy strategy = WechatMpMessageHandleStrategyFactory.getMessageHandleStrategy(wxMpMsgType);
        if (strategy != null) {
            responseMessage = strategy.handleMessage(xml);
        }
        response.setContentType("application/xml;charset=UTF-8");
        response.getWriter().write(responseMessage);
    }

    private boolean checkSignature(String signature, String timestamp, String nonce, String token) {
        String[] tmpArray = new String[]{token, timestamp, nonce};
        Arrays.sort(tmpArray);
        String tmpStr = Arrays.toString(tmpArray).replaceAll("\\[|]|,|\\s", "");
        String tmpSignature = WechatMpXmlUtil.sha1(tmpStr);
        return signature.equals(tmpSignature);
    }

}
